package com.bill99.codecheck.tools;

import info.monitorenter.cpdetector.io.CodepageDetectorProxy;
import info.monitorenter.cpdetector.io.JChardetFacade;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.nio.charset.Charset;

import org.apache.commons.io.FileUtils;

import com.bill99.riaframework.common.helper.Bill99Logger;

public class TranEncodeTool {
	private static Bill99Logger logger = Bill99Logger.getLogger(TranEncodeTool.class.getClass());

	public static void tranEncode(String temppath){
		

		File commitFile = new File(temppath);
		CodepageDetectorProxy detector = CodepageDetectorProxy.getInstance();
		detector.add(JChardetFacade.getInstance());
		Charset charset = null;
		try {
			charset = detector.detectCodepage(commitFile.toURI().toURL());
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (!charset.name().equals("UTF-8")) {
			logger.info("此工程代码格式非UTF-8");
			InputStream fInputStream = null;
			try {
				fInputStream = new FileInputStream(commitFile);
				ByteArrayOutputStream baos = new ByteArrayOutputStream();
				byte[] buffer = new byte[fInputStream.available()];
				int iLength = 0;
				while ((iLength = fInputStream.read(buffer)) != -1) {
					baos.write(buffer, 0, iLength);
				}
				fInputStream.close();
				baos.close();
				FileUtils.writeStringToFile(commitFile, baos.toString("GBK"), "UTF-8");
				logger.info("转码结束");
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
	}

}
	


